package koscom.corebase.nam;

import java.io.UnsupportedEncodingException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;

public class SClient {
	private String HOST="192.168.172.137";
    private int PORT=12333;
    SocketChannel channel = null;
    ByteBuffer readBuffer;
    OnListener ref;
    RcvThread rcvThread;
    
    interface OnListener {
		void onRcvData(ByteBuffer rcvBuff);
	}
    
    public void setListener(OnListener callback) {
		this.ref = callback;
		rcvThread.start();
	}
    
    public SClient(String host, int port, boolean blockingMode)
    {
    	if(host!=null) HOST=host;
    	if(port!=0) PORT=port;
    	try{
    		channel=SocketChannel.open(new InetSocketAddress(HOST,PORT));
    		channel.configureBlocking(blockingMode);
    	}catch(Exception e){}
    	readBuffer=ByteBuffer.allocateDirect(1024);
    	readBuffer.clear();
    	rcvThread = new RcvThread();
    }
    
    public void writeString(String string)
    {
    	try{
    		ByteBuffer buffer = toByteBuffer(string);
    		while (buffer.hasRemaining())
    			channel.write(buffer);
    	}catch(Exception e){System.out.println("에라");}
    }
    
    public void writeBuffer(ByteBuffer buffer)
    {
    	try{
//    	while (buffer.hasRemaining())
//	        channel.write(buffer);
    	channel.write(buffer);
    	}catch(Exception e){System.out.println("에라");}
    }
    
    public String read()
    {
    	String tmp = null;
    	try{
    		channel.read(readBuffer);
    		readBuffer.rewind();
    		tmp = toString(readBuffer);
    		System.out.println(tmp);
    	}catch(Exception e){System.out.println("??");}
    	return tmp;
    }
    
    public void close()
    {
    	try{
    		channel.close();
    	}catch(Exception e){}
    }
    
	public String toString(ByteBuffer buffer) throws UnsupportedEncodingException {
		byte[] bytes = new byte[buffer.remaining()];
		buffer.get(bytes);
		return new String(bytes, "UTF-8");
	}

	public ByteBuffer toByteBuffer(String value) throws UnsupportedEncodingException {
		return ByteBuffer.wrap(value.getBytes("UTF-8"));
	} 
	
	class RcvThread extends Thread {

		public void run() {

			while (true) {
				try {
					int readLen = channel.read(readBuffer);
					readBuffer.clear();
					if(readLen<=0)
					{
						Thread.sleep(100);
					}
					else
					{
						ref.onRcvData(readBuffer);
						readBuffer.clear();
						
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
	}
}
